/*
 * JSFConsole - Lightweight JSF Application Monitor
 * Copyright (C) 2009  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.jsfconsole.agent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import com.gregbugaj.jsfconsole.Constants;

/**
 * 
 * @author devil
 *
 */
public class TraceEventManager {
	private static Map<EventType, List<TraceEventListener>> listeners;
	private static List<String> listenerNames;
	static{
		listeners=new HashMap<EventType, List<TraceEventListener>>();
		listenerNames=new ArrayList<String>();
	}

	/**
	 * Fire all registered events for current event type making sure that 
	 * Request with header 'JSF-Console' will not be processed
	 * @param event to fire
	 */
	public static void fireEvent(TraceEvent traceEvent) {	
		//Check if this request is from from our console
		if(isConsoleRequest(traceEvent)){
			return;
		}

		EventType eventType=traceEvent.getEventType();
		List<TraceEventListener> lst = listeners.get(eventType);
		if(lst==null){
			lst=Collections.<TraceEventListener>emptyList();
		}

		for(TraceEventListener listener:lst){
			listener.trace(traceEvent);
		}
	}

	/**
	 * Check if given TraceEvent is a Event fired by our console
	 * @param traceEvent
	 * @return
	 */						
	private static boolean isConsoleRequest(TraceEvent traceEvent) {
		boolean retVal=false;
		FacesContext facesContex=(FacesContext) traceEvent.getArguments()[0];
		ExternalContext external = facesContex.getExternalContext();
		Map<String, String> headers = external.getRequestHeaderMap();
		for(String key:headers.keySet()){
			if(Constants.HEADER_KEY.equalsIgnoreCase(key)){
				retVal = true;
			}
		}
		return retVal;
	}

	/**
	 * Register new TraceEventListerner for given eventTypes
	 * Listener can be registered only once
	 * @param listener to register
	 * @param eventTypes to register listener for
	 */
	public static void registerListener(TraceEventListener listener, EventType... paramEventTypes){	
		System.out.println("TraceEventManager.registerListener() : "+listener.getListenerId());
		EventType[] eventTypes = paramEventTypes; 
		if(listener!=null){		
			//Check if the EventType.ANY have been passed
			//if so then we need to register this listener for all events
			if(paramEventTypes.length==1 && paramEventTypes[0].equals(EventType.ANY)){
				System.out.println("**** ---- TRACING ALL EVENTS ----- *********");
				EventType[] values=EventType.values();
				eventTypes=new EventType[values.length];
				int i=0;
				for (EventType e : values) {
					eventTypes[i++]=e;					           
				}				
			}
			System.out.println(" ** Registered");


			for(EventType eventType:eventTypes){
				System.out.println("     ** eventType :"+eventType.name());
				List<TraceEventListener> lst=listeners.get(eventType);
				if(lst==null){
					lst=new ArrayList<TraceEventListener>();
					listeners.put(eventType, lst);
				}
				String lKey=eventType.name()+":"+listener.getListenerId();
				if(!listenerNames.contains(lKey)){
					lst.add(listener);	
					listenerNames.add(lKey);
				}
			}
		}
	}

	/**
	 * Remove listener from registered list
	 * @param listener
	 * @param eventTypes
	 */
	public static void removeListener(TraceEventListener listener, EventType... eventTypes){
		if(listener!=null){		
			for(EventType eventType:eventTypes){
				List<TraceEventListener> lst=listeners.get(eventType);
				String lKey=eventType.name()+":"+listener.getListenerId();
				if(lst!=null && listenerNames.contains(lKey)){
					lst.remove(listener);	
					listenerNames.remove(lKey);
				}
			}
		}
	}

}
